package com.example.exam.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.exam.mapper.QuestionBankMapper;
import com.example.exam.pojo.QuestionBank;
import com.example.exam.service.QuestionBankService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author
 * @date 2023/03/06
 */
@Service
public class QuestionBankServiceImpl extends ServiceImpl<QuestionBankMapper, QuestionBank> implements QuestionBankService {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public void insert(QuestionBank questionBank) {
        baseMapper.insert(questionBank);
    }

    @Override
    public void batchInsert(String... strs) {
        baseMapper.deleteAll();
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        QuestionBankMapper questionBankMapper = sqlSession.getMapper(QuestionBankMapper.class);
        //在切割题目时，第一题前面生成一个空字符串
        for(int i = 1; i < strs.length; i++) {
            QuestionBank questionBank = new QuestionBank(i, strs[i]);
            questionBankMapper.insert(questionBank);
        }
        sqlSession.commit();
    }

    @Override
    public void updateTopicByTid(QuestionBank questionBank) {
        QueryWrapper<QuestionBank> wrapper = new QueryWrapper<>();
        wrapper.eq("tid", questionBank.getTid());
        baseMapper.update(questionBank, wrapper);
    }

    @Override
    public List<QuestionBank> searchQuestionBankList() {
        return baseMapper.selectList(null);
    }

    @Override
    public QuestionBank searchQuestionBank(int tid) {
        QueryWrapper<QuestionBank> wrapper = new QueryWrapper<>();
        wrapper.eq("tid", tid);
        return baseMapper.selectOne(wrapper);
    }
}
